package com.sneaker.shower.exception;

import com.sneaker.shower.common.BaseView;
import com.sneaker.shower.common.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @author zhaohongyang
 * @version 1.0
 * @className GlobalExceptionHandler
 * @date 2018/09/14 16:01
 * @description 全局异常拦截
 * @program holder-saas-aggregation-merchant
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * @param e exception
     * @return BaseView
     * @Validated 标签校验结果拦截
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseView validatedError(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> String.format("%s:%s", fieldError.getField(), fieldError.getDefaultMessage()))
                .collect(Collectors.joining(","));
        logger.warn("参数校验失败:{}", message);
        return new BaseView(message.split(":")[1], 801);
    }

    /**
     * 拦截所有异常信息
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public BaseView exception(BizException e) {
        if (logger.isErrorEnabled()) {
            logger.error("app聚合层系统异常：{}", e);
        }
        return new BaseView(e.getMessage(), 801);
    }

    /**
     * 拦截所有异常信息
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public BaseView exception(Exception e) {
        if (logger.isErrorEnabled()) {
            logger.error("app聚合层系统异常：{}", e);
        }
        return new BaseView("系统异常", 801);
    }
}
